package com.medicine.controller;


import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.medicine.common.CommonConstant;
import com.medicine.common.JsonMessageUtils;
import com.medicine.model.User;
import com.medicine.service.IUserService;


@Controller
public class LoginController {

	@Autowired
	private HttpServletRequest request;
	@Resource
	private IUserService userService;

	@RequestMapping(value="/register.html",method=RequestMethod.POST)
	@ResponseBody
	public String registerUser(@RequestBody Object param){
		String username = (String)((Map)param).get("username");
		String userpwd = (String)((Map)param).get("userpwd");
		System.out.println("username:"+username+",pwd:"+userpwd);
		try {
			String msg=null;
            JSONObject json = null;
			if("".equals(username) || "".equals(userpwd)){
				msg="请输入用户名或密码";
			}else{
				if(username.length()>8 || userpwd.length()>15){
					msg="用户名或密码过长";
				}else{
					User user = new User();
					user.setUsername(username);
					List<User> isExitUser = userService.selectByModel(user);
					if(null != isExitUser && isExitUser.size()>0){
						msg="用户名已存在！";
					}else{
						user.setLastlogintime(new Timestamp(System.currentTimeMillis()));
						user.setCreatetime(new Timestamp(System.currentTimeMillis()));
						user.setLoginstatus(0);
						user.setUserpwd(userpwd);
						int num = userService.insert(user);
						if(num>0){
							msg="恭喜，您注册成功！";
							json = new JSONObject();
							json.put("userid",user.getId());
						}else
							msg="sorry，系统异常！";
					}
				}
				
			}
			return JsonMessageUtils.getSuccessJson(msg, json);
		} catch (Exception e) {
			e.printStackTrace();
			return JsonMessageUtils.getErrorJson("抱歉，注册失败", null);
		}
	}

	@RequestMapping(value="/login.html",method=RequestMethod.POST)
	@ResponseBody
	public String loginUser(@RequestBody Object param){
		String username = (String)((Map)param).get("username");
		String userpwd = (String)((Map)param).get("userpwd");
		System.out.println("username:"+username+",pwd:"+userpwd);
		try {
			User model = new User();
			model.setUsername(username);
			model.setUserpwd(userpwd);
			String msg = null;
			JSONObject json = null;
			if("".equals(model.getUsername()) || "".equals(model.getUserpwd()) ){
				msg="用户名或密码为空";
			}else{
				List<User> users = userService.selectByModel(model);


				if(null == users || users.size()==0){
					msg = "用户:"+username+"不存在或错误";
				}else{
					model = users.get(0);
					model.setLastlogintime(new Timestamp(System.currentTimeMillis()));
					model.setLoginstatus(1);
					int isUpdate = userService.updateByPrimaryKey(model);//
					msg = "登录成功";
					json = new JSONObject();
					json.put("page", "../page/selecthouse.html?id="+model.getId());
					json.put("userid", model.getId());
					request.getSession().setAttribute(CommonConstant.LOGIN_USER, model);
				}
			}

			return JsonMessageUtils.getSuccessJson(msg, json);
		} catch (Exception e) {
			e.printStackTrace();
			return JsonMessageUtils.getErrorJson("抱歉，登陆失败", null);
		}

	}

	@RequestMapping(value="/loginOut.html",method=RequestMethod.POST)
	@ResponseBody
	public String loginOut(@RequestBody Object param){
        System.out.println("==================="+param.toString());
		String userId = (String)((Map)param).get("userId");
		 System.out.println("===================logOut userId"+userId);
		String msg = null;
		try {
			HttpSession session = request.getSession();
			User user = new User();
			user.setId(Integer.valueOf(userId));
			user.setLoginstatus(0);
			userService.updateByPrimaryKey(user);
			session.invalidate();
			JSONObject returnPage = new JSONObject();
			returnPage.put("page", "../page/index.html");
			return JsonMessageUtils.getSuccessJson("退出登录", returnPage);
		} catch (Exception e) {
			e.printStackTrace();
			return JsonMessageUtils.getErrorJson("退出登录异常", null);
		}
	}


	@RequestMapping(value="/loginOnline.html",method=RequestMethod.GET)
	@ResponseBody
	public String loginOnLine(){

		//String msg = null;
		try {
			Map<String, Object> model = new HashMap<String, Object>();
			model.put("loginstatus", 1);
			long num = userService.selectCountByMap(model);
			//msg = String.valueOf(num);
			return JsonMessageUtils.getSuccessJson("在线人数统计成功", num);
		} catch (Exception e) {
			e.printStackTrace();
			return JsonMessageUtils.getErrorJson("在线人数统计异常", null);
		}

	}

}
